<?php

namespace addons\yunfood\controller;

use addons\yunfood\library\Logic;
use addons\yunfood\library\Super;
use addons\yunfood\model\Shop as ShopModel;

/**
 * 门店接口
 */
class Shop extends BaseApi
{
    public $noNeedLogin = ['getShopList', 'getShopDetail'];

    // 获取门店列表
    public function getShopList()
    {
        $group = $this->request->post('group');

        // 数据列表
        $query = ShopModel::where('start_time != end_time')->show()
            ->order(['weight' => 'DESC', 'id' => 'DESC']);
        if ($group && $group !== 'all') {
            $time = date('Gi');
            if ($group === 'rest') {
                $query->where('(start_time<end_time and (start_time>' . $time . ' or ' . $time . '>=end_time)) or (start_time>end_time and start_time>' . $time . ' and ' . $time . '>=end_time)');
            } elseif ($group === 'ing') {
                $query->where('(start_time<end_time and start_time<=' . $time . ' and ' . $time . '<end_time) or (start_time>end_time and (start_time<=' . $time . ' or ' . $time . '<end_time))');
            }
        }

        $result = $query->paginate($this->request->post('page_size', 10), false);
        $result = Logic::getPageData($result, [
            'id',
            'name',
            'cover_url',
            'start_time' => 'start_time_text',
            'end_time'   => 'end_time_text',
            'address',
            'contact',
            'state'
        ]);

        $this->success('success', $result);
    }

    // 获取门店详情
    public function getShopDetail()
    {
        $shopId = $this->request->post('id');
        if (! $shopData = ShopModel::get($shopId)) {
            $this->error('门店数据不存在');
        }
        if ($shopData->status != ShopModel::STATUS_NORMAL) {
            $this->error('门店还未营业');
        }

        $result = Super::arrayGetSet($shopData, [
            'id',
            'name',
            'cover_url',
            'start_time' => 'start_time_text',
            'end_time'   => 'end_time_text',
            'address',
            'contact',
            'state'
        ]);

        $this->success('success', $result);
    }
}
